TypeScripting Cypress
https://gyazo.com/aa50d968a68da1936e93ddd738262053
I saw a description that says something like the following, which is not appropriate if you put tsconfig inside the cypress directory, otherwise it ignores the custom command
code:tsconfig.json
"include": [
"cypress/integration/*.ts",
"cypress/integration/**/*.ts",
]
It is a relative path, so it looks like this (FULL)
code:tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": [
"es5",
"dom"
],
"types": [
"cypress"
]
},
"include": [
"*.ts",
"**/*.ts",
"../src/*.ts",
"../src/**/*.ts",
]
}
When I tried to import *.tsx, I got an error that --jsx is required, but I decided to keep it simple since it was unclear whether I needed to be able to import tsx for this use case in the first place.
Typo is now properly alerted if you import { State } from "reactn/default"; and declare the type.
https://gyazo.com/cbbf38921672d36603034a047fa6e03c
By the way, about the @ts-ignore thing,
If cy.window().its("movidea").then((movidea) => { ... }, the argument is any,
cy.get("@movidea").then((movidea) => { ... } would be JQuery<HTMLElement>.
It is inconvenient to cast movidea every time.
Create custom commands or
I tried to follow the sample, but I had some problems like Type 'Chainable' is not generic. or `Property 'movidea' does not exist on type 'cy & EventEmitter'. I had a bit of trouble getting it to work, but I finally got it to work.
code:cypress/support/index.ts
/// <reference types="cypress" />
import { TMovidea } from "../../src/exposeGlobal";
declare global {
namespace Cypress {
interface Chainable {
movidea(callback: (movidea: TMovidea) => void): Chainable;
}
}
}
Cypress.Commands.add("movidea", (callback: (movidea: TMovidea) => void) => {
return cy.window().its("movidea").then(callback);
});
code:ts
declare namespace Cypress {
interface Chainable {
/**
* Custom command to select DOM element by data-cy attribute.
* @example cy.dataCy('greeting')
*/
dataCy(value: string): Chainable<Element>
}
}
I checked the Cypress source.
code:ts
declare global {
namespace Cypress {
// TODO: Why is Subject unused?
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface Chainable<Subject = any> {
...
So, I supplemented global and it works as expected.
Finally, in the test code, I could write this. It looks like a destructive update, but it is a non-destructive update using immer, and the redrawing by the React hook runs properly.
code:test.ts
cy.movidea((movidea) => {
movidea.updateGlobal((g) => {
});
});
---
This page is auto-translated from /nishio/CypressのTypeScript化. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. I'm very happy to spread my thought to non-Japanese readers.